package com.san.common.auth.controller.api;

import com.san.common.auth.dto.AuthToken;
import com.san.common.auth.dto.ResultDTO;
import com.san.common.auth.exception.ServiceException;
import com.san.common.auth.service.AdminService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.Principal;

@Controller
@RequestMapping("/api")
public class AdminController {

    @Resource
    AdminService adminService;

    @ResponseBody
    @GetMapping("/code")
    public ResultDTO getCode(@RequestParam("platform") String platform,
                             @RequestParam("redirect_url") String redirectUrl,
                             HttpServletRequest request,
                             HttpServletResponse response) throws Exception{
        Principal userPrincipal = request.getUserPrincipal();
        String username = userPrincipal.getName();
        String code = adminService.generateCode(username);
        String url = redirectUrl + "?code=" + code;
        response.sendRedirect(url);
        return ResultDTO.success("Ok", code);
    }

    @ResponseBody
    @GetMapping("/token/{code}")
    public AuthToken getToken(@PathVariable("code") String code,
                              HttpServletRequest request) {
        Principal userPrincipal = request.getUserPrincipal();
        String username = userPrincipal.getName();
        AuthToken authToken = adminService.getToken(code, username);
        if (authToken == null) throw new ServiceException("生成token失败");
        return authToken;
    }
}
